package com.pro.springbootshop.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
//用于参考的controller
@RestController
//@NoWapper设置无统一返回值
public class HelloController {
    @ApiOperation("hello测试")//API文档注释
    @GetMapping ("/hello")
    // http://location:5050/hello?nickname=zhangsan&phone=123
    public String hello(String nickname,String phone){
        return "hello world!!"+nickname+phone;
    }
    @GetMapping("/getTest1")//修改传递值的名字
    public String getTest1(@RequestParam(value="nickname",required = false) String name){
        return "Get:"+name;
    }
    @PostMapping("/postTest1")
    public  String postTest1(){
        return "POST请求";
    }
    @PostMapping("/postTest2")
    public  String postTest2(String username,String password){
        System.out.println(username);
        System.out.println(password);
        return "POST请求";
    }
    //文件上传
    @PostMapping("/upload")
    public String upload(String nickname, MultipartFile photo, HttpServletRequest request)throws IOException{
        System.out.println("文件大小:"+photo.getSize());
        System.out.println(photo.getOriginalFilename());
        String path=request.getServletContext().getRealPath("/upload/");
        System.out.println(path);
        //动态生成服务器的存储目录
        saveFile(photo,path);
        return "上传成功";
    }
    public void saveFile(MultipartFile photo,String path)throws IOException{
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdir();
        }
        File file=new File(path+photo.getOriginalFilename());
        photo.transferTo(file);
    }
}
